/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *    ------------------------------------------------------------------------
 *    Copyright (C) 2004-2006
 *    Salvatore Ruggieri
 *    Dipartimento di Informatica, Universita' di Pisa
 *    Pisa, Italy
 *    ------------------------------------------------------------------------
 *
 */

package LDA;

import java.io.*;
import java.sql.*;
import java.util.*;

public class DBUtil {

	/**
	 * Loading required JDBC drivers. JDBC drivers are included in the
	 * jdbcString, separated by ':'.
	 */
	public static void loadJDBC(String jdbcString) {
		StringTokenizer st = new StringTokenizer(jdbcString, ":");
		while (st.hasMoreTokens()) {
			String drv = st.nextToken();
			try {
				Class.forName(drv);
			} catch (ClassNotFoundException e) {
			}
		}
	}

	/**
	 * Output a ResultSet to a PrintWriter in the Comma Separated Values format.
	 * 
	 * @param rs
	 *            input ResultSet
	 * @param os
	 *            output PrintWriter
	 * @param metadata
	 *            true if column names and types have to be outputed
	 * @return number of rows in output
	 */
	public static void toCSV(ResultSet rs, PrintWriter os, boolean metadata)
			throws SQLException {
		ResultSetMetaData md = rs.getMetaData();
		int nCols = md.getColumnCount();
		if (metadata) {
			// output column names
			for (int i = 1; i < nCols; ++i)
				os.print(md.getColumnName(i) + ",");
			os.println(md.getColumnName(nCols));
			// output column types
			for (int i = 1; i < nCols; ++i)
				os.print(DBUtil.getColumnType(md, i) + ",");
			os.println(DBUtil.getColumnType(md, nCols));
		}
		// output result set
		while (rs.next()) {
			for (int i = 1; i < nCols; ++i)
				os.print(rs.getString(i) + ",");
			os.println(rs.getString(nCols));
		}
		// flush printwriter
		os.flush();
	}

	public static String getColumnType(ResultSetMetaData md, int column)
			throws SQLException {
		int type = md.getColumnType(column);

		switch (type) {
		case Types.CHAR:
		case Types.VARCHAR:
		case Types.LONGVARCHAR:
			return "String";

		case Types.BIT:
			return "Boolean";

		case Types.TINYINT:
		case Types.SMALLINT:
		case Types.INTEGER:
			return "int";

		case Types.BIGINT:
			return "long";

		case Types.FLOAT:
		case Types.DOUBLE:
			return "double";

		case Types.DATE:
			return "date";

		default:
			return "other";
		}
	}

	public static void toCSV(ResultSet rs) throws IOException, SQLException {
		PrintWriter output = IOUtil.getWriter("");
		toCSV(rs, output, false);
	}

	public static void toCSVmd(ResultSet rs) throws IOException, SQLException {
		PrintWriter output = IOUtil.getWriter("");
		toCSV(rs, output, true);
	}

	@SuppressWarnings("rawtypes")
	public static Class getColumnClass(ResultSetMetaData md, int column)
			throws SQLException {
		int type = md.getColumnType(column + 1);

		switch (type) {
		case Types.CHAR:
		case Types.VARCHAR:
		case Types.LONGVARCHAR:
			return String.class;

		case Types.BIT:
			return Boolean.class;

		case Types.TINYINT:
		case Types.SMALLINT:
		case Types.INTEGER:
			return Integer.class;

		case Types.BIGINT:
			return Long.class;

		case Types.FLOAT:
		case Types.DOUBLE:
			return Double.class;

		case Types.DATE:
			return java.sql.Date.class;

		case Types.TIMESTAMP:
			return java.sql.Timestamp.class;

		default:
			return Object.class;
		}
	}

	/**
	 * Returns whether a given table exists in a database.
	 * 
	 * @param dbmd
	 *            metadata on the connection
	 * @param tableName
	 *            tablename in the form [[catalog.]schema.]table
	 * @return true if such a table exists
	 */
	public static boolean exists(DatabaseMetaData dbmd, String tableName)
			throws SQLException {
		String catalog = null;
		String schema = null;
		String tname = tableName;
		int dot = tableName.lastIndexOf(".");
		if (dot != -1) {
			schema = tableName.substring(0, dot);
			tname = tableName.substring(dot + 1);
			dot = schema.lastIndexOf(".");
			if (dot != -1) {
				catalog = schema.substring(0, dot);
				schema = schema.substring(dot + 1);
			}
		}
		// asks for metadata of the required table
		ResultSet rs = dbmd.getTables(catalog, schema, tname, null);
		boolean res = rs.next();
		rs.close();
		return res;
	}
}
